// Memory Management Tools Implementation

import * as fs from 'fs';
import * as path from 'path';
import {
    ToolHandler,
    ToolResult,
    ToolExecutionContext,
    ValidationResult
} from '../core/interfaces';

interface MemoryItem {
    id: string;
    content: string;
    timestamp: Date;
    tags?: string[];
    metadata?: Record<string, any>;
}

/**
 * 记忆管理器 - 单例模式
 */
class MemoryManager {
    private static instance: MemoryManager;
    private memories: Map<string, MemoryItem> = new Map();
    private memoryCounter: number = 0;
    private memoryFile: string = '';

    static getInstance(): MemoryManager {
        if (!MemoryManager.instance) {
            MemoryManager.instance = new MemoryManager();
        }
        return MemoryManager.instance;
    }

    initialize(workspaceRoot: string): void {
        this.memoryFile = path.join(workspaceRoot, '.augment-memories.json');
        this.loadMemories();
    }

    private async loadMemories(): Promise<void> {
        try {
            if (fs.existsSync(this.memoryFile)) {
                const data = await fs.promises.readFile(this.memoryFile, 'utf8');
                const memoriesData = JSON.parse(data);
                
                for (const [id, memoryData] of Object.entries(memoriesData)) {
                    this.memories.set(id, {
                        ...(memoryData as any),
                        timestamp: new Date((memoryData as any).timestamp)
                    });
                }
                
                // 更新计数器
                this.memoryCounter = Math.max(...Array.from(this.memories.keys()).map(id => parseInt(id.split('_')[1]) || 0), 0);
            }
        } catch (error) {
            console.warn('Failed to load memories:', error);
        }
    }

    private async saveMemories(): Promise<void> {
        try {
            const memoriesData: Record<string, any> = {};
            for (const [id, memory] of this.memories.entries()) {
                memoriesData[id] = {
                    ...memory,
                    timestamp: memory.timestamp.toISOString()
                };
            }
            
            await fs.promises.writeFile(this.memoryFile, JSON.stringify(memoriesData, null, 2), 'utf8');
        } catch (error) {
            console.error('Failed to save memories:', error);
            throw error;
        }
    }

    async addMemory(content: string, tags?: string[], metadata?: Record<string, any>): Promise<MemoryItem> {
        const id = `memory_${++this.memoryCounter}`;
        const memory: MemoryItem = {
            id,
            content,
            timestamp: new Date(),
            tags,
            metadata
        };

        this.memories.set(id, memory);
        await this.saveMemories();
        
        return memory;
    }

    searchMemories(query: string, limit: number = 10): MemoryItem[] {
        const queryLower = query.toLowerCase();
        const results: MemoryItem[] = [];

        for (const memory of this.memories.values()) {
            // 简单的文本匹配搜索
            if (memory.content.toLowerCase().includes(queryLower) ||
                (memory.tags && memory.tags.some(tag => tag.toLowerCase().includes(queryLower)))) {
                results.push(memory);
            }
        }

        // 按时间倒序排序，返回最新的结果
        return results
            .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
            .slice(0, limit);
    }

    getAllMemories(): MemoryItem[] {
        return Array.from(this.memories.values())
            .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
    }

    getMemoryCount(): number {
        return this.memories.size;
    }

    clearMemories(): void {
        this.memories.clear();
        this.memoryCounter = 0;
    }
}

/**
 * 记忆创建工具
 */
export class RememberHandler implements ToolHandler {
    private memoryManager = MemoryManager.getInstance();

    async execute(parameters: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
        const { memory } = parameters;

        try {
            // 初始化记忆管理器
            this.memoryManager.initialize(context.workspaceRoot);

            // 创建记忆
            const memoryItem = await this.memoryManager.addMemory(memory);

            return {
                success: true,
                data: {
                    id: memoryItem.id,
                    content: memoryItem.content,
                    timestamp: memoryItem.timestamp.toISOString(),
                    message: 'Memory created successfully'
                }
            };
        } catch (error) {
            throw new Error(`Failed to create memory: ${error instanceof Error ? error.message : `${error}`}`);
        }
    }

    validate(parameters: Record<string, any>): ValidationResult {
        const errors: string[] = [];

        if (!parameters.memory || typeof parameters.memory !== 'string') {
            errors.push('memory parameter is required and must be a string');
        }

        if (parameters.memory && parameters.memory.trim().length === 0) {
            errors.push('memory parameter cannot be empty');
        }

        return {
            isValid: errors.length === 0,
            errors: errors
        };
    }
}

/**
 * 记忆检索工具
 */
export class MemoryRetrievalHandler implements ToolHandler {
    private memoryManager = MemoryManager.getInstance();

    async execute(parameters: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
        const { query, limit = 10 } = parameters;

        try {
            // 初始化记忆管理器
            this.memoryManager.initialize(context.workspaceRoot);

            // 搜索记忆
            const memories = this.memoryManager.searchMemories(query, limit);

            return {
                success: true,
                data: {
                    query: query,
                    results: memories.map(memory => ({
                        id: memory.id,
                        content: memory.content,
                        timestamp: memory.timestamp.toISOString(),
                        tags: memory.tags || []
                    })),
                    total_found: memories.length,
                    total_memories: this.memoryManager.getMemoryCount()
                }
            };
        } catch (error) {
            throw new Error(`Failed to retrieve memories: ${error instanceof Error ? error.message : `${error}`}`);
        }
    }

    validate(parameters: Record<string, any>): ValidationResult {
        const errors: string[] = [];

        if (!parameters.query || typeof parameters.query !== 'string') {
            errors.push('query parameter is required and must be a string');
        }

        if (parameters.query && parameters.query.trim().length === 0) {
            errors.push('query parameter cannot be empty');
        }

        if (parameters.limit !== undefined && (typeof parameters.limit !== 'number' || parameters.limit < 1)) {
            errors.push('limit parameter must be a positive number');
        }

        return {
            isValid: errors.length === 0,
            errors: errors
        };
    }
}
